package offer.list;

import java.util.ArrayList;
import java.util.Stack;

public class ReverseToArrayList {

    public ArrayList reverseListNodeToArrayList(ListNode node) {
        if (node == null) {
            return null;
        }

        ArrayList list = new ArrayList();
        Stack stack = new Stack();
        ListNode p = node;
        while (p != null) {
            stack.add(p.value);
            p = p.next;
        }

        while (!stack.isEmpty()) {
            list.add(stack.pop());
        }

        return list;
    }

    public ArrayList reverseByListNode(ListNode node) {
        ArrayList list = new ArrayList();
        if (node == null) {
            return list;
        }

        ListNode pre = null;
        ListNode now = node;
        while (now != null) {
            now = node.next;
            node.next = pre;
            pre = node;
            node = now;
        }

        while (pre != null) {
            list.add(pre.value);
            pre = pre.next;
        }

        return list;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode("0");
        ListNode p = head;
        String str = "";
        for (int i = 1; i < 9; i++) {
            str += i;
            p.next = new ListNode(str);
            p = p.next;
        }

        ArrayList list = null;
        ReverseToArrayList reverse = new ReverseToArrayList();

        //list = reverse.reverseListNodeToArrayList(head);
        //System.out.println(list.toString());

        list = reverse.reverseByListNode(head);
        System.out.println(list.toString());
    }
}
